﻿using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using ReagentStore.UTL;

namespace ReagentStore
{
	public class FormValidator
	{
		private readonly ErrorProvider _errorProvider;
		private readonly List<ValidatorBase> _validators = new List<ValidatorBase>();
		private bool _isValid = true;

		public FormValidator(ErrorProvider errorProvider)
		{
			_errorProvider = errorProvider;
		}

		public ValidatorBase this[Control control]
		{
			get { return _validators.SingleOrDefault(validator => ReferenceEquals(validator.Control, control)); }
		}

		public ErrorProvider ErrorProvider
		{
			get { return _errorProvider; }
		}

		public void Add(ValidatorBase validatorBase)
		{
			_validators.Add(validatorBase);
		}

		public void Remove(ValidatorBase validatorBase)
		{
			if (_validators.Count > 0)
				_validators.Remove(validatorBase);
		}

		public void Clear()
		{
			_validators.Clear();
		}

		public bool IsValid()
		{
			_isValid = true;
			foreach (ValidatorBase validator in _validators)
				_errorProvider.SetError(validator.Control, string.Empty);

			foreach (ValidatorBase validator in _validators)
				if (!validator.IsValid())
				{
					_errorProvider.SetError(validator.Control, validator.ErrorText);
					_isValid = false;
				}

			return _isValid;
		}
	}
}